package com.cmeduSystem.webadmin.upms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.cmeduSystem.common.core.annotation.DisableDataFilter;
import com.cmeduSystem.common.core.annotation.MyRequestBody;
import com.cmeduSystem.webadmin.upms.model.SysUser;
import com.cmeduSystem.webadmin.upms.service.SysUserService;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
@Tag(name = "发送短信接口")
@Slf4j
@RestController
@RequestMapping("/admin/upms/sysUser")
public class SnmpController {
    @Autowired
    private SysUserService sysUserService;
    @PostMapping({"/webhook"})
    public void handleWebhook(@MyRequestBody Long processorId,@MyRequestBody String title) {
        System.out.println("Received webhook payload: " + processorId);
        System.out.println("Received webhook payload: " + title);
        List<SysUser> userList =  sysUserService.getSysUserList(null,null);
        String[] phones = new String[userList.size()];
        for (int i = 0; i < userList.size(); i++) {
            if(processorId == (userList.get(i).getUserId())){
                phones[i] = userList.get(i).getMobile();
            }

        }


            for(String phone : phones) {
                this.send(phone, title);

                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


    }

    public void send(String phone, String msg) {
        String serverIp = "78.96.16.10";
        int serverPort = 20108;
        String message = "86" + phone + ":0:" + msg;
//        message = message.replaceAll("\ud83d\udd34 Down", "离线");
//        message = message.replaceAll("✅ Up", "在线");
//        System.out.println(message);
//        if (message.contains("离线")) {
//            return;
//        }

        try (Socket socket = new Socket(serverIp, serverPort)) {
            System.out.println("Connected to server at " + serverIp + ":" + serverPort);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(message.getBytes("GBK"));
            outputStream.flush();
            socket.close();
            System.out.println("Message sent: " + message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
